/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.googlecode.ivybeans.facade;

import java.io.File;
import java.io.FilenameFilter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.logging.Logger;
import org.apache.ivy.plugins.parser.xml.XmlModuleDescriptorParser;

/**
 *
 * @author xavier
 */
public class IvyFileUtil {

    public static Logger LOG = Logger.getLogger("com.googlecode.ivybeans.module");
    public static String DEFAULT_CHARSET = java.nio.charset.Charset.forName(new java.io.OutputStreamWriter(
            new java.io.ByteArrayOutputStream()).getEncoding()).name();

    public static URL getSchemaURL() {
        return XmlModuleDescriptorParser.class.getResource("ivy.xsd");
    }

    public static File discoverIvyJarFile() {
        File ivyJarFile = null;
        // load the Ivy api and get the path that points to the ivy.jar
        URL url = org.apache.ivy.Ivy.class.getProtectionDomain().getCodeSource().getLocation();
        // replace invalid characters by valid ones
        // directories that have spaces, %20, accents, are all sanitized
        String ivyjarpath = decodeURL(url);
        // it comes as "jar:file:///home/claudio/.../ivy.jar!/"
        // lets strip it to the following: /home/claudio/.../ivy.jar
        ivyjarpath = ivyjarpath.substring(9, ivyjarpath.indexOf("!/"));

        ivyJarFile = new File(ivyjarpath);
        if (ivyJarFile.exists()) {
            LOG.info("found ivy jar => " + ivyJarFile.getAbsolutePath());
}
        return ivyJarFile;
        /*
         *      -==== this is a alternative way to find the ivy.jar
        URL url = IvyPreferences.class.getProtectionDomain().getCodeSource().getLocation();
        String f = url.getPath();
        // strip the above string to resolve to the parent dir
        // this is intendend to see the ivy jar file
        f = f.substring(5, f.indexOf("com-googlecode")) + "ext";
        File ff = new File(f);
        LOG.fine("(ff) ivy beans path = " + ff);
        LOG.fine("(nb) FileUtil normalize= " + FileUtil.normalizeFile(ff));
        File[] ffs = ff.listFiles(new FilenameFilter() {

        public boolean accept(File dir, String name) {
        if (name.startsWith("ivy")) {
        return true;
        } else {
        return false;
        }
        }
        });
        LOG.fine("ffs == null ? " + (ffs == null));
        for (int i = 0; i < ffs.length; i++) {
        ivyJarFile = ffs[i];
        LOG.info("found ivy jar => " + ivyJarFile.getAbsolutePath());
        // just one ivy jar file is expected to be there
        break;
        }
        return ivyJarFile;
         */
    }

    /**
     * Try to find the ant lib jar file bundled with the Ivy NetBeans module
     * @return
     */
    public static File discoverAntlibJarFile() {
        // locate the directory where the ivybeans are installed
        URL url = IvyFileUtil.class.getProtectionDomain().getCodeSource().getLocation();
        // decode and sanitize the file path
        String moduleDir = decodeURL(url);
        // the antlib contrib is installed on the modules/ext/ directory
        moduleDir = moduleDir.substring(9, moduleDir.indexOf("com-googlecode")) + "ext";
        File ff = new File(moduleDir);
        // list all files, and get the ant-contrib.jar
        File[] ffs = ff.listFiles(new FilenameFilter() {

            public boolean accept(File dir, String name) {
                if (name.startsWith("ant-contrib")) {
                    return true;
                } else {
                    return false;
                }
            }
        });
        File antlibJarFile = null;
        for (int i = 0; i < ffs.length; i++) {
            antlibJarFile = ffs[i];
            LOG.info("found ant lib jar => " + antlibJarFile.getAbsolutePath());
            // just one ant lib jar file is expected to be there
            break;
        }
        return antlibJarFile;
    }

    /**
     *  decode windows path files (spaces, %20 chars)
     */
    public static String decodeURL(URL url) {
        try {
            return URLDecoder.decode(url.toString(), DEFAULT_CHARSET);
        } catch (final UnsupportedEncodingException e) {
            return url.toString();
        }

    }
}
